package com.woniuxy.mapper;

import java.util.List;

import org.apache.ibatis.annotations.*;

import com.woniuxy.entity.Perms;
import com.woniuxy.entity.Roles;

@Mapper
public interface RolesPermsMapper {
	// 查询用户角色
	@Select("select ur.u_id,ur.ro_id,r.type  from user_roles ur,roles r where ur.ro_id=r.ro_id and ur.u_id=#{u_id} ")
	@Results({ @Result(id = true, column = "ro_id", property = "ro_id"),
			@Result(column = "ro_id", property = "perms", many = @Many(select = "findPermsByRid")) })
	public List<Roles> findRolesByUid(int u_id);

	@Select("select * from roles")
	public List<Roles> allRoles();

	// 查询所有角色
	@Select("select * from roles")
	@Results({ @Result(id = true, column = "ro_id", property = "ro_id"),
			@Result(column = "ro_id", property = "perms", many = @Many(select = "findPermsByRid")) })
	public List<Roles> findRolesPerms();

	@Insert("insert into perms values(default,#{type})")
	public int addRoles(String type);

	@Delete("delete from perms where ro_id=#{ro_id}")
	public int delRoles(int pe_id);

	@Update("update perms set type=#{type} where ro_id=#{ro_id}")
	public int updateRoles(int pe_id, String type);

	// 用户添加角色
	@Insert({ "<script> insert into user_roles(u_id,ro_id) values"
			+ "<foreach  collection = 'ro_ids' item = 'ro_id' index = 'index' separator=','>"
			+ "	(#{u_id},#{ro_id}) " + "</foreach>" + "</script>" })
	public int addUserRoles(@Param("u_id") Integer u_id, @Param("ro_ids") int[] ro_ids);
	
	// 删除用户所有角色
	@Delete("delete from user_roles where u_id=#{u_id}")
	public int delUserRoles(int u_id);

	/* ----------------- */

	// 查询所有权限
	@Select("select * from perms")
	public List<Perms> allPerms();

	@Insert("insert into perms values(default,#{type})")
	public int addPerms(String type);

	@Delete("delete from perms where pe_id=#{pe_id}")
	public int delPerms(int pe_id);

	@Update("update perms set type=#{type} where pe_id=#{pe_id}")
	public int updatePerms(int pe_id, String type);

	// 增加角色的权限
	@Insert({ "<script> insert into roles_perms(ro_id,pe_id) values"
			+ "<foreach  collection = 'pe_ids' item = 'pe_id' index = 'index' separator=','>"
			+ "	(#{ro_id},#{pe_id}) " + "</foreach>" + "</script>" })
	public int addRolesPerms(@Param("ro_id") Integer ro_id, @Param("pe_ids") int[] pe_ids);

	// 删除角色的所有权限
	@Delete("delete from roles_perms where ro_id=#{ro_id}")
	public int delRolesPerms(int ro_id);

	/* ----------------- */

	// 查询角色的权限
	@Select("select rp.pe_id,p.type from roles_perms rp,perms p where rp.pe_id=p.pe_id and rp.ro_id=#{ro_id}")
	public List<Perms> findPermsByRid(int ro_id);

}
